<template>
  <div class="home-page">
    <div class="header">
      <div class="title-container">
        <p class="title-message">
          <span>律法测试</span>
        </p>
      </div>
    </div>

    <div class="greeting-section">
      <div class="greeting-card">
        <h3>你好，同学</h3>
        <p>准备好开始你的律法测试了吗？</p>
        <van-button type="primary" block round size="large" @click="toggleCategoryView" class="view-all-btn"
          :loading="loading">
          {{ showHotCategories ? '查看所有律法分类' : '查看热门分类' }}
        </van-button>
      </div>
    </div>

    <div class="categories-section">
      <div class="section-header">
        <h3>{{ showHotCategories ? '热门律法分类' : '全部分类' }}</h3>
        <van-icon v-if="showHotCategories" name="fire" color="#ee0a24" />
      </div>
      <van-loading v-if="loading" class="loading-indicator" />
      <div v-else class="categories-grid">
        <div v-for="(category, index) in currentCategories" :key="index" class="category-card"
          @click="goToCategory(category)">
          <div class="category-icon">
            <van-icon :name="getCategoryIcon(category.categoryName)" size="24" />
          </div>
          <div class="category-info">
            <h4>{{ category.categoryName }}</h4>
            <p class="category-desc">{{ category.description }}</p>
            <span>{{ category.questionCount }}个问题</span>
          </div>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
      </div>
    </div>

    <!-- 在categories-section中添加数量选择对话框 -->
    <van-dialog v-model:show="showQuestionCountDialog" title="选择题目数量" show-cancel-button @confirm="confirmQuestionCount"
      @cancel="cancelQuestionCount">
      <div class="count-dialog-content">
        <p>请选择测试题目数量 (1-{{ selectedCategory?.questionCount || 5 }})</p>
        <van-stepper v-model="selectedQuestionCount" :max="selectedCategory?.questionCount || 5" :min="1" />
      </div>
    </van-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getHotCategories, getAllCategories } from '@/api/category.ts'
import type { QuestionCategoryVO } from '@/types/question_category/QuestionCategoryVO'
import { ca } from 'element-plus/es/locales.mjs'
import { showToast } from 'vant'

const router = useRouter()


// 新增的状态
const showQuestionCountDialog = ref(false)
const selectedCategory = ref<QuestionCategoryVO | null>(null)
const selectedQuestionCount = ref(5) // 默认5题

// 确认题目数量
const confirmQuestionCount = () => {
  if (!selectedCategory.value) return
  
  // 验证题目数量
  const maxCount = selectedCategory.value.questionCount || 5
  if (selectedQuestionCount.value > maxCount) {
    showToast(`题目数量不能超过${maxCount}`)
    return
  }

  // 跳转到测试页面，传递分类编号和题目数量
  router.push({
    path: '/practice/test',
    query: { 
      categoryNo: selectedCategory.value.categoryNo,
      questionCount: selectedQuestionCount.value.toString()
    }
  })
  
  // 重置对话框状态
  showQuestionCountDialog.value = false
}

// 取消选择
const cancelQuestionCount = () => {
  showQuestionCountDialog.value = false
  selectedCategory.value = null
}

// 数据状态
const hotCategories = ref<QuestionCategoryVO[]>([])
const allCategories = ref<QuestionCategoryVO[]>([])
const showHotCategories = ref(true)
const loading = ref(false)

// 计算当前显示的分类
const currentCategories = computed(() => {
  return showHotCategories.value ? hotCategories.value : allCategories.value
})

// 修改goToCategory函数
const goToCategory = (category: QuestionCategoryVO) => {
  // 先保存选中的分类
  selectedCategory.value = category
  // 设置默认题目数量（不超过该分类最大题数）
  selectedQuestionCount.value = Math.min(5, category.questionCount || 5)
  // 显示题目数量选择对话框
  showQuestionCountDialog.value = true
}
// 切换分类视图
const toggleCategoryView = () => {
  showHotCategories.value = !showHotCategories.value
  loadCurrentData()
}


// 根据分类名称获取图标
const getCategoryIcon = (categoryName?: string) => {
  if (!categoryName) return 'notes-o'

  const iconMap: Record<string, string> = {
    '民法': 'balance-pay',
    '刑法': 'warning',
    '行政法': 'description',
    '劳动法': 'friends',
  }

  const matchedKey = Object.keys(iconMap).find(key =>
    categoryName.includes(key)
  )

  return matchedKey ? iconMap[matchedKey] : 'notes-o'
}

// 加载当前需要显示的数据
const loadCurrentData = async () => {
  loading.value = true
  try {
    if (showHotCategories.value) {
      if (hotCategories.value.length === 0) {
        const res = await getHotCategories()
        console.log(res.data.data);
        hotCategories.value = res.data.data || []
      }
    } else {
      if (allCategories.value.length === 0) {
        const res = await getAllCategories()
        console.log(res.data.data);
        allCategories.value = res.data.data || []
      }
    }
  } catch (error) {
    console.error('加载分类数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始加载热门分类数据
onMounted(() => {
  loadCurrentData()
})
</script>

<style scoped>
.home-page {
  padding: 0 16px 16px;
  background-color: #f7f8fa;
}

.header {
  position: relative;
  height: 70px;
  margin-bottom: 20px;
}

.title-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background: linear-gradient(135deg, #1989fa, #3296fa);
  border-bottom-left-radius: 50% 40%;
  border-bottom-right-radius: 50% 40%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  padding-bottom: 20px;
}

.title-message {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.greeting-section {
  margin-bottom: 24px;
}

.greeting-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.1);
}

.greeting-card h3 {
  margin-top: 0;
  font-size: 25px;
  color: #050505;
}

.greeting-card p {
  color: #666;
  margin-bottom: 16px;
}

.view-all-btn {
  margin-top: 12px;
  background: linear-gradient(135deg, #1989fa, #3296fa);
  border: none;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #05101b;
}

.section-header h3 {
  margin: 0;
  margin-right: 8px;
  font-size: 25px;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.categories-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.category-card {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 4px rgba(25, 137, 250, 0.1);
  transition: transform 0.2s;
  position: relative;
  /* 添加相对定位 */
}

.category-card:active {
  transform: scale(0.98);
}

.category-icon {
  width: 40px;
  height: 40px;
  background: #e6f0fd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #1989fa;
}


.category-info {
  flex: 1;
  /* 确保中间内容区域占据剩余空间 */
  margin-right: 12px;
  /* 添加右边距，避免箭头太靠近文字 */
  min-width: 0;
  /* 添加这一行，确保文本截断生效 */
}

.category-info h4 {
  margin: 0 0 6px 0;
  /* 增加下边距 */
  font-size: 16px;
  color: #1989fa;
  font-weight: 500;
}

.category-desc {
  margin: 0 0 6px 0;
  color: #666;
  font-size: 13px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  /* 限制显示2行 */
  -webkit-box-orient: vertical;
  max-height: 2.8em;
  /* 两行文字的高度 */
}

.category-info span {
  color: #7dacec;
  font-size: 12px;
}

.category-info span {
  color: #7d828a;
  font-size: 14px;
}

.arrow-icon {
  color: #7dacec;
  margin-left: auto;
  /* 使用自动左边距将箭头推到最右侧 */
  padding-left: 12px;
  /* 添加一些内边距 */
  flex-shrink: 0;
  /* 防止箭头被挤压 */
}

/* 新增对话框样式 */
.count-dialog-content {
  padding: 24px 16px;
  text-align: center;
}

.count-dialog-content p {
  margin-bottom: 20px;
  color: #333;
}
</style>